package cn.bgs.controller;

import cn.bgs.common.AliOss;
import cn.bgs.service.UserService;
import cn.bgs.common.R;
import cn.bgs.utils.RedisUtil;
import cn.bgs.vo.RandomUtil;
import cn.bgs.vo.Txuser;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private AliOss aliOss;

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("/login/{userName}/{password}")
    public R login(@PathVariable("userName")String userName, @PathVariable("password") String password){

        log.info("登录账号密码：{}",userName+"+"+password);

        Txuser txuser = new Txuser();
        txuser.setUuid(RandomUtil.getSixBitRandom());
        txuser.setName(userName);
        txuser.setPassword(password);
        txuser.setAvatar("/static/images/Avatar-2.png");
        Map<Object,Object> map =new HashMap<>();
        map.put(txuser.getName(), JSON.toJSON(txuser));

        redisUtil.hmset("user",map);

        return userService.login(userName, password).data("user",txuser);
    }

    /**
     * 注册
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("/register/{userName}/{password}")
    public R register(@PathVariable("userName")String userName, @PathVariable("password") String password){

        log.info("注册账号密码：{}",userName+"+"+password);



        return userService.register(userName, password);
    }

    /**
     * 图片上传
     * @param file
     * @return
     */
    @RequestMapping("/addPic")
    public String addPic(MultipartFile file){
        String upload = aliOss.upload(file);
        System.out.println(upload);
        return upload;
    }


    @GetMapping("/findtxuser")
    @ApiOperation(value = "通讯信息查询")
    public R findtxuser(@RequestParam String name){

        Map<Object, Object> user = redisUtil.hmget("user");
        List<Object> objects= new ArrayList<>();;
        if (user.containsKey(name)){
             user.remove(name);
            user.forEach((key,value)->{
                    objects.add(value);
            });
        }

        return R.ok().data("findtxuser" , objects);
    }
}
